package com.jet.chat.service;

import com.jet.chat.dbquery.ChatQueryCheckAuth;
import com.jet.chat.dbquery.ChatQueryCheckAuthParams;
import com.jet.chat.dbquery.ChatQueryCheckAuthResult;
import com.jet.chat.exception.ChatException;
import com.jet.chat.message.MessageQueue;
import com.jet.chat.message.MessageReader;
import com.jet.chat.server.ChatServer;


public class ChatAccessService {
	private ChatServer chatServer;
	private int id;
	private String username;
	private String password;
	
	private final int MAX_ATTEMTS_COUNT = 3;
	
	public ChatAccessService(ChatServer chatServer) {
		this.chatServer = chatServer;
	}

	public synchronized void checkAuth(MessageReader reader, MessageQueue queue) throws Exception {
		int attempts = 0;
		while (this.id == 0 && attempts < MAX_ATTEMTS_COUNT) {
			
			username = inputData(reader, queue, "enter username");
			password = inputData(reader, queue, "enter password");
			
			checkId(queue);
			attempts++;
		}
		SendCommandToQuitIfMadeThreeAttempts(queue, attempts);
	}

	private void checkId(MessageQueue queue) throws Exception {
		ChatQueryCheckAuthParams params = new ChatQueryCheckAuthParams(username, password);
		ChatQueryCheckAuthResult result = (ChatQueryCheckAuthResult) new ChatQueryCheckAuth().execute(chatServer.getDBConnectionService(), params);
		this.id = result.getUserId();
		
		if (this.id == 0) {
			queue.addMessage("wrong username-password. retype");
		} else {
		}
	}

	private String inputData(MessageReader reader, MessageQueue queue, String command) throws ChatException {
		queue.addMessage(command);
		return reader.read().getContent();
	}

	private void SendCommandToQuitIfMadeThreeAttempts(MessageQueue queue, int count) throws ChatException {
		if (count == MAX_ATTEMTS_COUNT) {
			queue.addMessage("three times with no valid. goodbye");
			queue.addMessage("/q");
		}
	}

	public int getId() {
		return id;
	}

	public String getUsername() {
		return username;
	}

}
